package com.cheng.xbjy.controller;

import com.cheng.xbjy.entity.Article;
import com.cheng.xbjy.entity.User;
import com.cheng.xbjy.entity.vo.PageResult;
import com.cheng.xbjy.entity.vo.Result;
import com.cheng.xbjy.service.ArticleService;
import com.cheng.xbjy.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;


    /**
     * 查询文章列表(带分页)
     *
     * @param title
     * @param page
     * @return
     */
    @GetMapping("/findPage/{page}")
    public Result findPage(String title, @PathVariable("page") Integer page) {
        Page<Article> pageData = articleService.findPage(title, page);
        return new Result(true, "查询成功"
                , new PageResult<Article>(pageData.getTotalPages(), pageData.getContent()));
    }

    /**
     * 发布文章
     *
     * @param article
     * @return
     */
    @PostMapping("/add")
    public Result addArticle(@RequestBody Article article) {
        User loginUser = LoginUserUtil.getLoginUser();
        articleService.save(article, loginUser);
        return new Result(true, "发布成功");
    }

    /**
     * 查看文章详情
     *
     * @param articleId
     * @return
     */
    @GetMapping("/detail/{articleId}")
    public Result findDetail(@PathVariable("articleId") Long articleId) {
        Map<String, Object> map = articleService.findDetail(articleId, LoginUserUtil.getUserId());
        return new Result(true, "查询成功", map);
    }

    /**
     * 收藏或取消收藏
     *
     * @param articleId
     * @return
     */
    @GetMapping("/favorite/{articleId}")
    public Result doFavorite(@PathVariable("articleId") Long articleId) {
        return articleService.doFavorite(articleId, LoginUserUtil.getUserId());
    }

    /**
     * 查看收藏的文章列表
     *
     * @param page
     * @return
     */
    @GetMapping("/findFavoritePage/{page}")
    public Result findFavoritePage(String title, @PathVariable("page") Integer page) {
        Page<Article> pageData = articleService.findFavoritePage(title, page, LoginUserUtil.getUserId());
        return new Result(true, "查询成功"
                , new PageResult<Article>(pageData.getTotalPages(), pageData.getContent()));
    }

}
